<template>
  <div class="content" ref="searchRef">
    <div class="parent" :class="{ 'parent-focus': menuDialog.visible }">
      <div class="prefix" @click.stop="showAllFun">{{ searchSource.name }}</div>
      <input v-model="searchKey" style="background: none;background-color: transparent;"
        placeholder="输入检索内容，试试输入 csdn 可以指定搜索服务哦" @keyup.enter.stop="search()" />
      <i class="fa-solid fa-magnifying-glass" @click="search()"></i>
    </div>
    <teleport to="body">
      <transition name="a-dialog-fade">
        <div class="tip context-menu" v-if="menuDialog.visible"
          :style="{ left: `${menuDialog.x + (showAll ? 10 : 70)}px`, bottom: menuDialog.bottom + 'px' }">
          <div style="font-size: 10px;color: var(--font-second-color);margin: 0 4px;text-align: center;">Tab切换源</div>
          <div class="tip-item" v-for="(item, index) in prefixFilter" :key="index"
            :class="{ 'actived': searchIndex == index || item.id === searchSource.id }" @click="selectItem(item)">
            <div class="title">{{ item.name }}</div>
            <div class="icon" style="width: 20px;line-height: 24px;margin-left: 6px;margin-right: -6px;"
              @click.stop="deleteSource(item);" v-if="showAll && !item.sys">
              <i class="fa-regular fa-trash-can" style="font-size: 12px;color: var(--error-color);"></i>
            </div>
          </div>
          <div class="icon" style="text-align: center;width: 40px;line-height: 24px;margin: 0 auto;"
            @click.stop="showAddDialog()" v-if="showAll">
            <i class="fa-solid fa-plus"></i>
          </div>
        </div>
      </transition>
    </teleport>

    <a-dialog v-model="addDialog.visible" :shake="!!addDialog.errorMessage">
      <div class="dialog-title">添加搜索源</div>
      <div style="margin-bottom:8px;display: flex;align-items: center;">
        <label>名称：</label>
        <input class="input" style="flex: 1;" v-model="addDialog.name" maxlength="6" placeholder="最多6个字" />
      </div>
      <div style="margin-bottom:8px;display: flex;align-items: center;">
        <label>地址：</label>
        <input class="input" style="flex: 1;" v-model="addDialog.url" maxlength="400" placeholder="跳转地址" />
      </div>
      <div style="font-size: 12px;color: var(--font-second-color);margin: 0 4px;">地址的关键字使用{KEY},如baidu.com?pw={KEY}
      </div>
      <div v-if="addDialog.errorMessage" style="color: var(--error-color);margin: 10px;text-align: center;">{{
        addDialog.errorMessage }}</div>
      <div style="text-align:right;margin-top: 20px;">
        <button class="button" @click.stop="addDialog.visible = false">取消</button>
        <button class="button btn-primary" @click.stop="add()">确定</button>
      </div>
    </a-dialog>
  </div>
</template>

<script>
export default {
  name: "a-search",
}
</script>
<script setup>
import { storage } from '@/lib/storage';
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import ADialog from "@/components/a-dialog.vue";
const showAll = ref(false);
const sysfixList = ref([{
  id: 0,
  name: "百度",
  sys: true,
  url: "https://www.baidu.com/s?wd={KEY}"
}, {
  id: 1,
  name: "必应",
  sys: true,
  url: "https://cn.bing.com/search?q={KEY}"
}, {
  id: 2,
  name: "CSDN",
  sys: true,
  url: "https://so.csdn.net/so/search?q={KEY}"
}]);
const prefixList = ref([]);

const menuDialog = ref({
  x: 0,
  bottom: 0,
  visible: false
});
const searchRef = ref(null);
const prefixFilter = ref([]);
const userSearchSource = ref([]);
const addDialog = ref({
  visible: false,
  errorMessage: '',
  name: '',
  url: '',
  id: ''
})
const searchIndex = ref(-1);
const searchKey = ref("");
const searchSource = ref({
  ...sysfixList.value[0],
  selected: true,
});

const selectItem = (item) => {
  searchSource.value = {
    ...item,
    selected: true,
  };
  storage.set('searchSource', JSON.stringify(searchSource.value));
}
const showAllFun = () => {
  showAll.value = true;
  prefixFilter.value = prefixList.value
  changeShow();
}
const closeMenu = () => {
  showAll.value = false;
  changeShow();
}
const deleteSource = (item) => {
  for (let i = 0; i < userSearchSource.value.length; i++) {
    if (userSearchSource.value[i].id === item.id) {
      console.log(1)
      if (searchSource.value.id === item.id) {
        if (searchIndex.value >= 1) {
          searchIndex.value = searchIndex.value - 1;
          searchSource.value = prefixFilter.value[searchIndex.value]
        } else {
          searchSource.value = prefixFilter.value[0]
        }
      }
      userSearchSource.value.splice(i, 1)
    }
  }
  prefixList.value = sysfixList.value.concat(userSearchSource.value);
  prefixFilter.value = prefixList.value
  storage.set('userSearchSource', JSON.stringify(userSearchSource.value));
  storage.set('searchSource', JSON.stringify(searchSource.value));
}
const showAddDialog = () => {
  addDialog.value.errorMessage = '';
  addDialog.value.name = '';
  addDialog.value.url = '';
  addDialog.value.visible = true;
  showAll.value = false;
  changeShow();
}

const add = () => {
  if (!addDialog.value.name) {
    addDialog.value.errorMessage = '名称不能为空';
    return;
  } else if (!addDialog.value.url) {
    addDialog.value.errorMessage = '地址不能为空';
    return;
  }
  addDialog.value.visible = false;
  userSearchSource.value.push({
    id: Date.now(),
    name: addDialog.value.name,
    url: addDialog.value.url,
  });
  prefixList.value = sysfixList.value.concat(userSearchSource.value);
  storage.set('userSearchSource', JSON.stringify(userSearchSource.value));
}
const handleKeyDown = (e) => {
  if (e.key === 'Tab') {
    e.preventDefault();
    searchIndex.value = (searchIndex.value + 1) % prefixFilter.value.length;
    if (prefixFilter.value.length === 1 || showAll.value) {
      confirmSelect();
    }
  } else if (e.key === 'Enter') {
    showAll.value = false;
    confirmSelect();
  }
};

const confirmSelect = () => {
  if (prefixFilter.value.length > 0 && searchIndex.value >= 0) {
    selectItem(prefixFilter.value[searchIndex.value]);
    let name = prefixFilter.value[searchIndex.value].name.toLowerCase();
    for (let i = name.length - 1; i >= 0; i--) {
      let c = name.charAt(i);
      if (c === ' ') {
        searchKey.value = searchKey.value.substring(0, searchKey.value.length - 1);
        continue;
      }
      if (searchKey.value.charAt(searchKey.value.length - 1).toLowerCase() === c) {
        searchKey.value = searchKey.value.substring(0, searchKey.value.length - 1);
      }
    }
    storage.set('searchSource', JSON.stringify(searchSource.value));
  }
}

onMounted(() => {
  window.addEventListener('keydown', handleKeyDown);
  document.addEventListener('click', closeMenu);

  storage.get('userSearchSource').then((r) => {
    if (r) {
      userSearchSource.value = JSON.parse(r);
      prefixList.value = sysfixList.value.concat(userSearchSource.value);
    } else {
      userSearchSource.value = [];
      prefixList.value = sysfixList.value;
    }
  });
  storage.get('searchSource').then((r) => {
    if (r) {
      searchSource.value = JSON.parse(r);
    }
  }); // 获取 searchRef 的位置信息

});

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown);
  document.removeEventListener('click', closeMenu);
})

const search = () => {
  if (searchKey.value) {
    window.open(searchSource.value.url.replace("{KEY}", searchKey.value).replace("{key}", searchKey.value), "_blank");
    searchKey.value = "";
  }
}
const changeShow = () => {

  const rect = searchRef.value.getBoundingClientRect();
  menuDialog.value.x = rect.left;
  menuDialog.value.bottom = document.body.offsetHeight - rect.top;
  menuDialog.value.visible = showAll.value || (prefixFilter.value.length > 0
    && searchKey.value
    && (!searchSource.value || !searchSource.value.selected))

}

watch(() => searchKey.value, (newVal) => {
  searchIndex.value = -1;
  searchSource.value.selected = false;
  prefixFilter.value = prefixList.value.filter(item => item.name.toLowerCase().indexOf(newVal.trim().toLowerCase()) >= 0 && item.id !== searchSource.value.id);
  changeShow();
});
</script>

<style scoped lang="less">
.content {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0 10px;
  height: 100%;
  cursor: move;
  box-sizing: border-box;

  .parent:hover,
  .parent.parent-focus {
    border-radius: 10px;
    opacity: 1;
  }

  .parent {
    padding: 10px 15px;
    display: flex;
    align-items: center;
    width: 100%;
    opacity: 0.8;
    background-color: var(--content-background-color);
    border-radius: 40px;
    transition: all 0.3s ease-in-out;
    overflow: hidden;
    /* 半透明 */
    backdrop-filter: blur(10px);
    /* 兼容老版本 Safari */
    -webkit-backdrop-filter: blur(10px);



    .prefix {
      cursor: pointer;
      font-size: 1rem;
      font-weight: 500;
      color: var(--primary-color-hover);
    }

    input {
      color: var(--font-color-deep);
      flex: 1;
      border: none;

      &::placeholder {
        color: var(--font-second-color);
      }

      &:hover {
        border: none;
      }
    }
  }


}

.tip {
  position: absolute;
  bottom: 40px;
  background-color: var(--content-background-color);
  left: 60px;
  padding: 4px 0;
  border-radius: 10px;
  /* 半透明 */
  backdrop-filter: blur(10px);
  /* 兼容老版本 Safari */
  -webkit-backdrop-filter: blur(10px);

  .tip-item {
    padding: 6px 15px;
    font-size: 1rem;
    font-weight: 500;
    cursor: pointer;
    display: flex;
    align-items: center;
    text-align: center;

    .title {
      flex: 1;
    }

    &:hover {
      font-weight: bolder;
      color: var(--primary-color-hover);
    }
  }

  .actived {
    font-weight: bolder;
    color: var(--primary-color-hover);
  }
}
</style>